// app.js
import api from '/utils/api.js';
import network from '/utils/network.js';

App({
    onLaunch() {
        //强制小程序重启并使用新版本
        let updateManager = wx.getUpdateManager();
        updateManager.onUpdateReady(function () {
            updateManager.applyUpdate();
        })
        this.getUserInfo().then(res => {
            console.log(res, '13131313131');
            this.getVipList();
        });
    },

    /**
     * 获取用户信息
     */
    getUserInfo: function () {
        let that = this;
        return new Promise(function (resolve, reject) {
            if (that.globalData.userInfo) {
                console.log('本地中获取用户信息');
                that.globalData.openId = that.globalData.userInfo.openid;
                resolve(that.globalData.userInfo);
            } else {
                wx.login({
                    success: res => {
                        console.log(res)
                        if (res.code) {
                            //发起网络请求
                            network.getJsonUnLoadding(api.getUserInfo, {
                                jsCode: res.code
                            }).then(result => {
                                const openId = result.data.openId
                                that.globalData.openId = openId;
                                that.globalData.userInfo = result.data
                                resolve(that.globalData.userInfo);
                            })
                        } else {
                            console.log('登录失败！' + res.errMsg)
                        }
                    },
                    fail: err => {
                        console.log(err)
                    }
                })
            }
        })
    },

    getVipList() {
        let that = this;
        return new Promise(function (resolve, reject) {
            if (that.globalData.vipList) {
                resolve(that.globalData.vipList);
            } else {
                network.getJson(api.dictType, {
                    type: 'vip_price'
                }).then(res => {
                    that.globalData.vipList = res.data;
                    resolve(that.globalData.vipList);
                })
            }
        })
    },
    getDistance(lat1, lng1, lat2, lng2) {
        var dis = 0;
        var radLat1 = lat1 * Math.PI / 180;
        var radLat2 = lat2 * Math.PI / 180;
        var deltaLat = radLat1 - radLat2;
        var deltaLng = lng1 * Math.PI / 180 - lng2 * Math.PI / 180;
        var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
        return dis * 6378137;
    },

    globalData: {
        debug: true,
        openId: '',
        userInfo: null,
        latitude: 30.49984,
        longitude: 114.34253,
        distance: 300,
        vipList: null,
        version: 'v1.0.11'
    }
})